<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-select
            v-model="industryParams.industryId"
            style="margin-bottom: 20px"
            placeholder="请选择"
            @change="changeIndustry"
          >
            <el-option
              v-for="item in industryOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
        <!-- <el-form-item label="所属行业" prop="dictId">
          <el-select v-model="queryParams.dictId" placeholder="请选择">
            <el-option
              v-for="item in industryOptions"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <div class="head-container tree-container">
          <el-tree
            :data="dictOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            ref="tree"
            @node-click="handleNodeClick"
            :highlight-current="true"
            node-key="id"
            :default-expanded-keys="defaultExpandkeys"
            accordion
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          v-show="showSearch"
          :inline="true"
          label-width="80px"
          @submit.native.prevent
        >
          <!-- <el-form-item label="部门" prop="dictId">
            <treeselect 
              v-model="queryParams.dictId" 
              :options="dictOptions" 
              :show-count="true" 
              placeholder="请选择部门" 
              style="width: 240px"
              size="small"
            />
          </el-form-item> -->
          <el-form-item label="关键字" prop="keywords">
            <el-input
              v-model="queryParams.keywords"
              placeholder="请输入标题名称"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
              size="small"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <!-- :disabled="this.currentId == null" -->
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              :disabled="this.currentId == null"
              v-hasPermi="['12110']"
              @click="handleAdd"
              >添加</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd2"
            >添加同级</el-button>
          </el-col> -->
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="tableList" :border="true">
          <!-- <el-table-column label="所属行业" prop="titleName" align="center" /> -->
          <el-table-column label="分类名称" prop="titleName" align="center" />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['12120']"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                v-hasPermi="['12130']"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.currentPage"
          :limit.sync="queryParams.pagesize"
          @pagination="getList"
        />
        <!-- 添加或修改角色配置对话框 -->
        <el-dialog
          :title="title"
          :visible.sync="open"
          width="500px"
          append-to-body
          :class="{ 'add-person': !form.id && currAction != 'sameLevel' }"
        >
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            :validate-on-rule-change="false"
            label-width="80px"
          >
            <!-- 添加 上级类别默认显示，可修改 -->
            <el-form-item
              v-if="!form.id && currAction != 'sameLevel'"
              label="上级类别"
              prop="dictId"
            >
              <treeselect
                v-model="form.dictId"
                :options="dictOptions"
                :show-count="true"
                placeholder="请选择上级类别"
              />
            </el-form-item>
            <!-- 修改、添加子级 上级类别默认显示，不可修改 -->
            <!-- <el-form-item v-if="form.id || currAction==='sameLevel'" label="上级类别">
              <el-input v-model="currentNodeVal" disabled />
            </el-form-item> -->

            <el-form-item label="标题名称" prop="titleName">
              <el-input v-model="form.titleName" placeholder="请输入标题名称" />
            </el-form-item>
            <el-form-item label="位置排序" prop="sort">
              <el-input-number
                v-model="form.sort"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getPage,
  listData,
  getData,
  delData,
  addData,
  updateData,
  getClassTree,
} from "@/api/system/industryClass";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getDict } from "@/api/select";

export default {
  name: "industryClass",
  components: { Treeselect },
  data() {
    return {
      dictOptions: undefined,
      currentId: null,
      currentTid: null,
      defaultExpandkeys: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      queryParams: {
        currentPage: 1,
        pagesize: 10,
        industryId: undefined,
        dictId: undefined,
        keywords: undefined,
      },
      showSearch: true,
      loading: true,
      tableList: [],
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      title: "",
      open: false,
      form: {},
      rules: {
        titleName: [
          { required: true, message: "标题名称不能为空", trigger: "blur" },
        ],
        dictId: [
          { required: true, message: "请选择上级类别", trigger: "change" },
        ],
        sort: [
          { required: true, message: "位置排序不能为空", trigger: "blur" },
        ],
      },
      rules3: {},
      industryParams: {
        industryId: undefined,
        industry: undefined,
        topLevel: 1,
      },
      industryOptions: [], //所属行业下拉框
      currAction: "", //当前动作
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getPageInfo();
  },
  methods: {
    getPageInfo() {
      getDict(1, 1).then((response) => {
        // 1-所属行业 1
        this.industryOptions = response.result.data; //所属行业
        if (this.industryOptions.length > 0) {
          this.industryParams.industryId = response.result.data[0].id;
          this.industryParams.industry = response.result.data[0].label;
        }
        this.getTree();
      });
    },
    getTree() {
      getClassTree(this.industryParams).then((response) => {
        console.log("response---", response);
        this.dictOptions = response.result.industryClassification;
        console.log(response.result);
        if (response.result.industryClassification.length > 0) {
          this.currentId = response.result.industryClassification[0].id;
          this.currentTid = response.result.industryClassification[0].tid;
          this.currentNodeVal = response.result.industryClassification[0].label;
        } else {
          this.currentId = null;
        }
        this.$nextTick(() => {
          //默认当前选中（主要是为了样式）
          this.$refs.tree.setCurrentKey(this.currentId, true, false);
        });
        this.getList();
      });
    },
    // 所属行业下拉框 节点单击事件
    changeIndustry(val) {
      this.industryParams.industry = val
        ? this.industryOptions.find((ele) => ele.id === val).label
        : "";
      this.getTree();
    },
    // 树 节点单击事件
    handleNodeClick(data) {
      this.currentId = data.id;
      this.currentTid = data.tid; //tid
      this.currentNodeVal = data.label;
      this.getList();
    },
    getList() {
      this.loading = true;
      if (this.currentId === null) {
        this.loading = false;
        this.tableList = [];
      } else {
        this.queryParams.industryId = this.industryParams.industryId;
        this.queryParams.dictId = this.currentId;
        listData(this.queryParams).then((response) => {
          this.tableList = response.result.rows;
          this.total = response.result.total;
          this.loading = false;
        });
      }
    },
    handleQuery() {
      this.queryParams.currentPage = 1;
      this.getList();
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    handleAdd2() {
      this.reset();
      this.currAction = "sameLevel";
      this.form.tid = 0;
      this.form.dictId = 0;
      this.open = true;
      this.title = "添加同级"; //上级id 顶级id都传0
    },
    handleUpdate(row) {
      this.reset();
      const theId = row.id || this.ids;
      getData(theId).then((response) => {
        this.form = response.result;
        this.form.dictId = this.currentId;
        this.open = true;
        this.title = "修改";
      });
    },
    submitForm() {
      console.log(this.industryParams.industryId);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateData(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getTree();
              // this.getList();
            });
          } else {
            addData(this.form).then((response) => {
              this.msgSuccess("添加成功");
              this.open = false;
              this.getTree();
              // this.getList();
            });
          }
        }
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        industryId: this.industryParams.industryId,
        industry: this.industryParams.industry,
        tid: this.currentTid === 0 ? this.currentId : this.currentTid,
        dictId: this.currentId,
        titleName: undefined,
        sort: 0,
      };
      this.resetForm("form");
      this.currAction = "";
    },
    handleDelete(row) {
      const theId = row.id;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          // 调接口
          return delData(theId);
        })
        .then(() => {
          this.getTree();
          // this.getList();
          this.msgSuccess("删除成功");
        });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children,
      };
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
  },
};
</script>

<style scoped lang="scss">
/* treeselect */
.vue-treeselect__input {
  display: block;
}
/deep/ .vue-treeselect__control {
  height: 32px;
  line-height: 32px;
  margin-top: 3px;
}
.add-person /deep/ .el-dialog__body {
  min-height: 240px;
}
</style>